package com.itheima.service.impl;

import com.itheima.mapper.BookMapper;
import com.itheima.mapper.BorrowMapper;
import com.itheima.pojo.Borrow;
import com.itheima.service.BorrowService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class BorrowServiceImpl implements BorrowService {

    @Autowired
    private BorrowMapper borrowMapper;
    @Autowired
    private BookMapper bookMapper;

    @Override
    public void borrow(Integer bookId, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId = (Integer) JwtUtils.
                parseJWT(token).
                get("id");
        bookMapper.reduceNum(bookId);
        Borrow borrow = new Borrow();
        borrow.setUserId(userId);
        borrow.setBookId(bookId);
        borrow.setCreateTime(LocalDateTime.now());
        borrow.setUpdateTime(LocalDateTime.now());
        borrowMapper.insert(borrow);
    }

    @Override
    public List<Borrow> display(HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer userId = (Integer) JwtUtils.parseJWT(token).get("id");
        List<Borrow> list = borrowMapper.getByUserId(userId);
        return list;
    }

    @Override
    public void returnBook(Integer id) {
        Borrow borrow = borrowMapper.getById(id);
        bookMapper.addNum(borrow.getBookId());
        borrowMapper.delete(id);

    }
}
